<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<style>
    #myCanvas {
        border: 1px solid #ddd;
        display: block;
        width: 300px;
        height: 300px;
    }


    .img-box {
        position: relative;

    }


    .btn-box {
        position: relative;
        width: 100px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        border-radius: 5px;
        color: #fff;
        background-color: deepskyblue;
    }

    .show-img {
        width: 100%;
    }

    .body-content {
        margin: 100px auto;
        display: flex;
        justify-content: space-around;
    }

    #fileBtn {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0;
        z-index: 10;
    }

    .corp-wrapper {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
    }

    .corp-box {
        position: absolute;
        top: 0;
        left: 0;
        width: 300px;
        height: 300px;
        border: 1px dashed #b6a7dd;
    }

    .btn {
        display: inline-block;
        width: 100px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        color: #fff;
        background-color: deepskyblue;
        border-radius: 5px;
    }

    body {
        background-color: #ededed;
    }
</style>

<body>
<div class="btn-box">
    图片上传
    <input type="file" onchange="changeImg(this)" id="fileBtn">
</div>


<div class="body-content">
    <div class="img-box">
        <img class="show-img">
        <div class="corp-wrapper">
            <div class="corp-box"></div>
        </div>
    </div>
</div>
<canvas width="300" height="300" id="myCanvas"></canvas>

<div>
    <span class="btn" onclick="corpPic()">裁剪</span>
</div>
</body>
<script>

    function changeImg(ev) {
        if (ev.files[0]) {
            getImgBase64Data(ev.files[0], function (result) {
                document.querySelector(".show-img").src = result;
            });
        }
    }


    function getImgBase64Data(file, callback) {
        var reader = new FileReader();
        reader.onload = function (e) {
            callback(e.target.result);
        };
        reader.readAsDataURL(file); // 读取完后会调用onload方法
    }


    function corpPic() {
        let corpBox = document.querySelector(".corp-box");
        let width = corpBox.clientWidth;
        let height = corpBox.clientHeight;
        let left = corpBox.offsetLeft;
        let top = corpBox.offsetTop;
        let imgSource = document.querySelector(".show-img");
        let ctx = document.getElementById("myCanvas").getContext("2d");
        ctx.drawImage(imgSource, left,top, width, height, 0, 0, 300, 300)
    }


</script>
</html>